package com.css.fxfzfxqh.modules.largeScreen.service;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.base.response.RestResponse;
import com.css.fxfzfxqh.modules.buildingIndividual.param.param;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.CalculationTasks;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.repository.CalculationTasksRepository;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.repository.CasualtiesDERepository;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.economicLossDE.repository.EconomicLossEDRepository;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.repository.ResistEarthquakesDERepository;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.casualtiesPE.repository.CasualtiesPERepository;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.economicLossPE.repository.EconomicLossPDRepository;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.resistEarthquakesPE.repository.ResistEarthquakesPERepository;
import com.css.fxfzfxqh.modules.largeScreen.LargeScreenDao;
import com.css.fxfzfxqh.modules.largeScreen.entity.*;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.model.entity.FxqhAssessEdQhResult;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.model.entity.FxqhAssessPdQhResult;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.repository.EnterAssessQhRepository;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.repository.impl.ProbabilityAssessQhRepository;
import com.css.fxfzfxqh.util.PlatformObjectUtils;
import com.css.fxfzfxqh.util.UUIDGenerator;
import com.css.fxfzfxqh.zcpt.sys.entity.Area;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.crypto.paddings.ZeroBytePadding;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Dbj
 * @date 2024年05月20日  14:34
 */
@Service
public class LargeScreenService {

    @Resource
    LargeScreenDao largeScreenDao;
    @Resource
    SysAreaService sysAreaService;
    @Resource
    private CalculationTasksRepository calculationTasksRepository;
    @Resource
    ResistEarthquakesDERepository resistEarthquakesDERepository;
    @Resource
    CasualtiesDERepository casualtiesDERepository;
    @Resource
    EconomicLossEDRepository economicLossEDRepository;
    @Resource
    ResistEarthquakesPERepository resistEarthquakesPERepository;
    @Resource
    CasualtiesPERepository casualtiesPERepository;
    @Resource
    EconomicLossPDRepository economicLossPDRepository;
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    EnterAssessQhRepository enterAssessQhRepository;
    @Resource
    ProbabilityAssessQhRepository probabilityAssessQhRepository;

    public RestResponse getEarthquakeDisasterRiskAssessment(String code,String type) {
        JSONObject js = new JSONObject();
        List<String> taskIdList = new ArrayList<>();
        if(StringUtils.isNotBlank(code) && "0".equals(code)){
            //全国的
            taskIdList = calculationTasksRepository.getAllTask("大屏展示");
        }else{
            //指定省的
            //根据code查询区域id
            Area area  = sysAreaService.getAreaByCode(code);
            if(PlatformObjectUtils.isNotEmpty(area)){
                taskIdList = calculationTasksRepository.getAllTask(area.getUuid());
            }
        }
        List<RiskEstimateData> list = new ArrayList<>();

        //确定
        //结构破坏
        List<Calculation> resistList = resistEarthquakesDERepository.getValue(taskIdList,code);
        Map<String, List<Calculation>> jgMap = resistList.stream().collect(Collectors.groupingBy(Calculation::getAreaName));
        //人员死亡
        List<Calculation> deathList = casualtiesDERepository.getValue(taskIdList, code, "1");
        Map<String, List<Calculation>> swMap = deathList.stream().collect(Collectors.groupingBy(Calculation::getAreaName));
        //人员重伤
        List<Calculation> injureList = casualtiesDERepository.getValue(taskIdList, code, "2");
        Map<String, List<Calculation>> zsMap = injureList.stream().collect(Collectors.groupingBy(Calculation::getAreaName));
        //经济损失
        List<Calculation> economicList = economicLossEDRepository.getValue(taskIdList, code);
        Map<String, List<Calculation>> jjMap = economicList.stream().collect(Collectors.groupingBy(Calculation::getAreaName));
        Iterator<String> iterator = jgMap.keySet().iterator();
        while(iterator.hasNext()){
            String district = iterator.next();
            String id = sysAreaService.getIdByCondition(district, "", "");
            String areaCode = JSONObject.parseObject(sysAreaService.getDivisionCodeById(id),String.class);

            Map<String, List<Calculation>> jgIntensityMap = jgMap.get(district).stream().collect(Collectors.groupingBy(Calculation::getIntensity));
            Map<String, List<Calculation>> swIntensityMap = swMap.get(district).stream().collect(Collectors.groupingBy(Calculation::getIntensity));
            Map<String, List<Calculation>> zsIntensityMap = zsMap.get(district).stream().collect(Collectors.groupingBy(Calculation::getIntensity));
            Map<String, List<Calculation>> jjIntensityMap = jjMap.get(district).stream().collect(Collectors.groupingBy(Calculation::getIntensity));
            for(int i=1;i<=5;i++){
                RiskEstimateData riskEstimateData = new RiskEstimateData();
                BigDecimal jgVal = PlatformObjectUtils.isNotEmpty(jgIntensityMap.get(i+""))?jgIntensityMap.get(i+"").get(0).getVal():BigDecimal.ZERO;
                BigDecimal swVal = PlatformObjectUtils.isNotEmpty(swIntensityMap.get(i+""))?swIntensityMap.get(i+"").get(0).getVal():BigDecimal.ZERO;
                BigDecimal zsVal = PlatformObjectUtils.isNotEmpty(zsIntensityMap.get(i+""))?zsIntensityMap.get(i+"").get(0).getVal():BigDecimal.ZERO;
                BigDecimal jjVal = PlatformObjectUtils.isNotEmpty(jjIntensityMap.get(i+""))?jjIntensityMap.get(i+"").get(0).getVal():BigDecimal.ZERO;
                riskEstimateData.setId(UUIDGenerator.getUUID()).setIntensity(i+"").setInjured(zsVal.doubleValue()).setEconomyLoss(jjVal.doubleValue())
                        .setDeath(swVal.doubleValue()).setRiskValue(jgVal.doubleValue()).setAssessType("1").setAreaCode(areaCode).setProvince(district);
                list.add(riskEstimateData);
            }
        }


        //概率
        //结构破坏
        resistList = resistEarthquakesPERepository.getValue(taskIdList,code);
        jgMap = deathList.stream().collect(Collectors.groupingBy(Calculation::getAreaName));

        //人员死亡
        deathList = casualtiesPERepository.getValue(taskIdList, code, "1");
        swMap = deathList.stream().collect(Collectors.groupingBy(Calculation::getAreaName));
        //人员重伤
        injureList = casualtiesPERepository.getValue(taskIdList, code, "2");
        zsMap = injureList.stream().collect(Collectors.groupingBy(Calculation::getAreaName));
        //经济损失
        economicList = economicLossPDRepository.getValue(taskIdList, code);
        jjMap = economicList.stream().collect(Collectors.groupingBy(Calculation::getAreaName));
        Iterator<String> gliterator = jgMap.keySet().iterator();
        while(gliterator.hasNext()){
            String district = gliterator.next();
            String id = sysAreaService.getIdByCondition(district, "", "");
            String areaCode = JSONObject.parseObject(sysAreaService.getDivisionCodeById(id),String.class);
            RiskEstimateData riskEstimateData = new RiskEstimateData();
            BigDecimal jgVal = jgMap.get(district).get(0).getVal();
            BigDecimal swVal = swMap.get(district).get(0).getVal();
            BigDecimal zsVal = zsMap.get(district).get(0).getVal();
            BigDecimal jjVal = jjMap.get(district).get(0).getVal();
            riskEstimateData.setId(UUIDGenerator.getUUID()).setProvince(district).setInjured(zsVal.doubleValue()).setEconomyLoss(jjVal.doubleValue())
                    .setDeath(swVal.doubleValue()).setRiskValue(jgVal.doubleValue()).setAreaCode(areaCode).setAssessType("2").setProvince(district);
            list.add(riskEstimateData);
        }

        js.put("result",list);
        return RestResponse.succeed(js);

    }

    public JSONObject getRiskZonation() {
        JSONObject js = new JSONObject();
        List<AssessQh> qhList = new ArrayList<>();
        List<String> taskIdList = calculationTasksRepository.getAllTask("大屏展示");
        if(PlatformObjectUtils.isNotEmpty(taskIdList) && taskIdList.size()>0){
            for (String taskId : taskIdList) {
                CalculationTasks task = calculationTasksRepository.findById(taskId);
                // 0为确定评估1为概率评估
                String assessType = task.getAssessType();
                if("0".equals(assessType)){
                    List<FxqhAssessEdQhResult> assessEdQhList = enterAssessQhRepository.getAssessEdQhList(taskId);
                    if(PlatformObjectUtils.isNotEmpty(assessEdQhList) && assessEdQhList.size()>0){
                        assessEdQhList.forEach(fxqhAssessEdQhResult -> {
                            AssessQh qh = new AssessQh();
                            qh.setId(fxqhAssessEdQhResult.getId()).setProvince(fxqhAssessEdQhResult.getProvince()).setCity(fxqhAssessEdQhResult.getCity())
                                    .setCounty(fxqhAssessEdQhResult.getCounty()).setGeom(fxqhAssessEdQhResult.getGeom()).setCondition(fxqhAssessEdQhResult.getCondition())
                                    .setQhLevel(fxqhAssessEdQhResult.getQhLevel()).setEstimateObj(fxqhAssessEdQhResult.getEstimateObj()).setAssessType(assessType).setGeomText(fxqhAssessEdQhResult.getGeomText());
                            qhList.add(qh);
                        });
                    }
                }else{
                    List<FxqhAssessPdQhResult> assessPdQhList = probabilityAssessQhRepository.getAssessPdQhList(taskId);
                    if(PlatformObjectUtils.isNotEmpty(assessPdQhList) && assessPdQhList.size()>0){
                        assessPdQhList.forEach(fxqhAssessEdQhResult -> {
                            AssessQh qh = new AssessQh();
                            qh.setId(fxqhAssessEdQhResult.getId()).setProvince(fxqhAssessEdQhResult.getProvince()).setCity(fxqhAssessEdQhResult.getCity())
                                    .setCounty(fxqhAssessEdQhResult.getCounty()).setGeom(fxqhAssessEdQhResult.getGeom()).setCondition("")
                                    .setQhLevel(fxqhAssessEdQhResult.getQhLevel()).setEstimateObj(fxqhAssessEdQhResult.getEstimateObj()).setAssessType(assessType).setGeomText(fxqhAssessEdQhResult.getGeomText());
                            qhList.add(qh);
                        });
                    }
                }
            }
        }
        js.put("result",qhList);
        return js;
    }

    public JSONObject getKeyNote() {
        JSONObject js = new JSONObject();
        List<KeynoteData> list = jdbcTemplate.query("select * from fxqh_keynote", new BeanPropertyRowMapper<>(KeynoteData.class));
        js.put("result",PlatformObjectUtils.isEmpty(list) || list.size()==0?new ArrayList<>():list);
        return js;
    }
}
